package com.my.juc.callable;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/3/5 21:00
 */

/**
 * CyclicBarrier
 * 只有当达到阈值的时候才会唤醒线程，没到阈值之前会一直处于等待状态
 */
public class CyclicBarrierDemo {
    
    // 创建固定值
    private static final int NUMBER = 7;

    public static void main(String[] args) {
        // 创建CyclicBarrier
        CyclicBarrier cyclicBarrier = new CyclicBarrier(NUMBER,() -> {
            System.out.println("集齐七颗龙珠就可以召唤神龙");
        });
        // 集齐七颗龙珠
        for (int i = 0; i < 7; i++) {
            new Thread(() -> {
                
                try {
                    System.out.println(Thread.currentThread().getName() + " 星龙珠被收集到");
                    // 等待
                    cyclicBarrier.await();
                    System.out.println("已许愿");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            }, i + 1 + "").start();
        }
    }
    
}
